﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FCA.Dto;
using System.IO;

namespace FCA.DataAccesss {
    public class HasseDataReader {
        public static List<Concept> ReadData(string fileName) {
            List<Concept> concepts = new List<Concept>();
            try {
                // Create an instance of StreamReader to read from a file.
                // The using statement also closes the StreamReader.
                using (StreamReader sr = new StreamReader(fileName)) {
                    String line;
                    // Read and display lines from the file until the end of
                    // the file is reached.

                    //tidset # item set
                    //1 2 4 # 3
                    int index = 0;
                    while ((line = sr.ReadLine()) != null) {
                        //Console.WriteLine(line);
                        string[] temp = line.Split('#');
                        Concept c = new Concept();
                        c.Items = new ItemSet(GetHashSetInt(temp[1]));
                        c.Tids = new TidSet(GetHashSetInt(temp[0]));
                        c.ID = index++;
                        concepts.Add(c);
                    }
                }
            }
            catch (Exception e) {
                // Let the user know what went wrong.
                Console.WriteLine("The file could not be read:");
                Console.WriteLine(e.Message);
            }
            return concepts;
        }

        private static HashSet<int> GetHashSetInt(string p) {
            HashSet<int> temp = new HashSet<int>();
            if (!string.IsNullOrEmpty(p)) {
                string[] strInts = p.Split(' ');
                foreach (string item in strInts) {
                    int t = -1;
                    if (int.TryParse(item, out t)) {
                        temp.Add(t);
                    }
                }
            }
            return temp;
        }
    }
}
